<template>
    <div class="ct-bodySet">
        <el-container>
            <el-header class="bgclr-dk-sp0 mb20 headerCoster">
                <el-row>
                    <el-col :span="20">
                        <el-breadcrumb  separator-class="el-icon-arrow-right">
                            <el-breadcrumb-item :to="{ path: '/mainPage/welcome' }">首页</el-breadcrumb-item>
                            <el-breadcrumb-item>角色权限管理</el-breadcrumb-item>
                            <el-breadcrumb-item :to="{ path: '/mainPage/userManage' }">用户管理</el-breadcrumb-item>
                            <el-breadcrumb-item v-if="editPara==='see'"><span class="main-Clr-ft">查看用户</span></el-breadcrumb-item>
                            <el-breadcrumb-item v-else-if="editPara==='edit'"><span class="main-Clr-ft">编辑用户</span></el-breadcrumb-item>
                            <el-breadcrumb-item v-else><span class="main-Clr-ft">添加用户</span></el-breadcrumb-item>
                        </el-breadcrumb>
                    </el-col>
                    <el-col :span="4" class="textAlignRight buttonLineHeight">
                        <el-button type="text" class="main-Clr-ft" icon="el-icon-back" @click="backOffBtn" size="small">返回</el-button>
                    </el-col>
                </el-row>
            </el-header>

            <el-container  class="pl20 pr20">
                <!--<el-main class="bgclr-dk-sp0">-->
                    <el-card class="cardWidth">
                        <div slot="header" v-if="editPara==='see'">
                            <span>查看用户信息</span>
                            <span class="fltRt cardButton">
                                <el-button type="primary" @click="editUser()" size="small"><div class="ft12p">编辑</div></el-button>
                            </span>
                        </div>
                        <div slot="header" v-else-if="editPara==='edit'">
                            <span>编辑用户信息</span>
                        </div>
                        <div slot="header" v-else>
                            <span>添加用户</span>
                        </div>

                        <!--:disabled='isEdit'-->
                        <el-form
                                :model="formData"
                                ref="formData"
                                :rules="formRules">
                            <el-form-item label="账号:" prop="accountName" label-width="19%">
                                <span v-if="editPara==='see'">{{formData.accountName}}</span>
                                <el-input v-else v-model.trim="formData.accountName" placeholder="请输入账号" size="small" class="width77" maxlength="24"></el-input>
                            </el-form-item>

                            <el-form-item label="用户名:" prop="userName" label-width="19%">
                                <span v-if="editPara==='see'">{{formData.userName}}</span>
                                <el-input v-else v-model.trim="formData.userName" placeholder="请输入用户名" size="small" class="width77" maxlength="128"></el-input>
                            </el-form-item>

                            <el-form-item label="邮箱:"  prop="emailAddress" label-width="19%">
                                <span v-if="editPara==='see'">{{formData.emailAddress}}</span>
                                <el-input v-else v-model.trim="formData.emailAddress" placeholder="请输入用户名" size="small" class="width77" maxlength="100"></el-input>
                            </el-form-item>

                            <el-form-item label="所属组:" label-width="19%" prop="groupIdList">
                                <div v-if="editPara==='see'" class="width77 orgUrTag">
                                    <el-tag :key="tag.id" v-for="tag in affGroup" class="mr5" type="info">
                                        {{tag.groupName}}
                                    </el-tag>
                                </div>
                                <div v-else class="width77 orgUrTag">
                                    <span v-if="affGroup.length>0" class="mr5">
                                        <el-tag :key="tag.id" v-for="tag in affGroup" class="mr5" type="info">
                                            {{tag.groupName}}
                                        </el-tag>
                                    </span>
                                    <el-button class="main-Clr-ft" @click="clickGroup" size="small">
                                        <span class="main-Clr-ft">点击选择所属组</span>
                                    </el-button>
                                </div>
                            </el-form-item>
                            <el-dialog
                                    class="elDialogUI"
                                    title="选择所属组"
                                    :visible.sync="groupDiagloSign"
                                    width="30%">
                                <div class="dialogHeght">
                                    <el-tree :data="groupTreeData"
                                             show-checkbox
                                             node-key="id"
                                             ref="groupTreeData"
                                             :props="groupTreeDataProps"
                                             default-expand-all
                                             check-strictly="true"
                                             :expand-on-click-node="false"
                                             :highlight-current="true">
                                    </el-tree>
                                </div>
                                <span slot="footer" class="dialog-footer">
                                        <el-button @click="orgCancel" size="small" class="bkmgColor">取 消</el-button>
                                        <el-button type="primary" @click="groupDetermine" size="small">确 定</el-button>
                                </span>
                            </el-dialog>

                            <el-form-item label="所属角色:" prop="roleIdList" label-width="19%">
                                <div v-if="editPara==='see'" class="width77 orgUrTag">
                                    <el-tag :key="tag.id" v-for="tag in affRole" class="mr5" type="info">
                                        {{tag.roleName}}
                                    </el-tag>
                                </div>
                                <div v-else class="width77 orgUrTag">
                                    <span class="mr5" v-if="affRole.length>0">
                                        <el-tag :key="tag.id" v-for="tag in affRole" class="mr5" type="info">
                                            {{tag.roleName}}
                                        </el-tag>
                                    </span>
                                    <el-button class="main-Clr-ft" @click="clickRole" size="small">
                                        <span class="main-Clr-ft">点击选择所属角色</span>
                                    </el-button>
                                </div>
                            </el-form-item>
                            <el-dialog
                                    class="elDialogUI"
                                    title="选择所属角色"
                                    :visible.sync="roleDiagloSign"
                                    width="30%">
                                <div class="dialogHeght">
                                    <el-tree :data="roleTreeData"
                                             ref="roleTreeData"
                                             :props="roleTreeDataProps"
                                             default-expand-all
                                             show-checkbox
                                             @check-change="handleClick"
                                             :expand-on-click-node="false"
                                             :highlight-current="true"
                                             node-key="id">
                                    </el-tree>
                                </div>
                                <span slot="footer" class="dialog-footer">
                                        <el-button @click="roleCancel" size="small" class="bkmgColor">取 消</el-button>
                                        <el-button type="primary" @click="roleDetermine" size="small">确 定</el-button>
                                </span>
                            </el-dialog>

                            <el-form-item label="用户说明:" prop="summary" label-width="19%">
                                <span v-if="editPara==='see'">{{formData.summary}}</span>
                                <el-input v-else placeholder="请输入用户说明" type="textarea" :autosize="{minRows: 4, maxRows: 6}" v-model.trim="formData.summary" maxlength="100" class="width77"></el-input>
                                <div v-if="editPara!=='see'" class="textAlignRight clr-dk-sp5 mb15 countNumber">{{formData.summary.length}}/100</div>
                            </el-form-item>


                            <el-form-item v-if="editPara==='edit'||!editPara">
                                <el-button type="primary" @click="submitForm('formData')" size="small" class="submitButton">提交</el-button>
                            </el-form-item>
                        </el-form>
                    </el-card>
                <!--</el-main>-->
            </el-container>
            <div class="bottomLayoutBus"></div>
        </el-container>
    </div>
</template>

<script>
    import urlConfig from '../../../config/url.json';
    import Vue from 'vue';
    import {  Message } from 'element-ui';

    Vue.component(Message.name, Message);

    let userUrl = urlConfig.userManage;
    let groupUrl = urlConfig.groupManage;
    let roleUrl = urlConfig.roleManage;
    let viewUrl = urlConfig.viewUser;

    export default {
        data () {
            //校验账号是否重复
            var checkAccountName = (rule, value, callback) => {
                let that=this;
                if(that.parameter.id){
                    //参数不为空，查看、编辑，校验其余
                    for(let i=0;i<that.allUser.length;i++){
                        if(that.parameter.id!=that.allUser[i].id){
                            if (value===that.allUser[i].accountName ) {
                                callback(new Error('账号已经存在，请更换！'));
                            }
                        }else{

                        }
                    }
                }else{
                    //参数为空，添加，校验全部
                    for(let j=0;j<that.allUser.length;j++){
                        if (value===that.allUser[j].accountName ) {
                            callback(new Error('账号已经存在，请更换！'));
                        }else{

                        }
                    }
                }
                callback();
            };

            //校验所属机构是否为空
            var checkGroup = (rule, value, callback) => {
                if (value.length==0 ) {
                    callback(new Error('必填信息'));
                }
                callback();
            };

            //校验所属机构是否为空
            var checkRole = (rule, value, callback) => {
                if (value.length==0 ) {
                    callback(new Error('必填信息'));
                }
                callback();
            };

            return {
                groupDiagloSign: false,            //控制对话框是否显示
                roleDiagloSign: false,
                editPara:'',
                parameter:'',
                affGroup:[],        //所属组List
                affRole:[],             //所属角色List
                // orgFlag:false,               //所属机构标记--用来校验所属机构的选择项是否为空-->显示表单项下面的校验信息
                // roleFlag:false,
                formData: {
                    affGroupFlag:'',           //所属组标记--用来校验所属机构的选择项是否为空-->显示前面的红点
                    affRoleFlag:'',         //所属角色标记

                    "id":'',
                    "accountName":"",               //账号
                    "userName":"",                  //用户名
                    "emailAddress":"",
                    "nickName":"",
                    "enable":"",
                    "summary":'',                     //用户说明
                    "groupIdList":[],                   //所属组idlist
                    "roleIdList":[],                  //所属角色IDList
                },
                allUser:[],               //所有用户，做重名校验
                formRules: {
                    accountName: [
                        { validator: checkAccountName,trigger: 'blur' },
                        { required: true,message:'必填信息' },
                        { max: 24, message: '最长24个字符', trigger: 'blur' }
                        ],
                    userName: [
                        { required: true,message:'必填信息' },
                        { max: 128, message: '最长128个字符', trigger: 'blur' }
                        ],
                    emailAddress: [
                        { required: true,message:'必填信息' },
                        { max: 100, message: '最长100个字符', trigger: 'blur' }
                        ],
                    groupIdList: [
                        { validator: checkGroup },
                        { required: true,message:'必填信息',trigger: 'blur' }
                        ],
                    roleIdList: [
                        { validator: checkRole },
                        { required: true,message:'必填信息',trigger: 'blur' }
                        ]
                },


                groupTreeDisorde:[],                   //未排序的组织机构数据
                groupTreeData : [],

                groupTreeDataProps:{
                    children: 'children',
                    label: 'groupName',
                },
                roleTreeDisorde:[],                   //未排序的角色机构数据
                roleTreeData : [],
                roleTreeDataProps:{
                    children: 'children',
                    label: 'roleName',
                },
            }
        },
        methods: {

            //单选
            handleClick(data, checked, node){
                let that=this;
                if(checked == true){
                    that.checkedId = data.id;
                    that.$refs.roleTreeData.setCheckedNodes([data]);
                }
            },
            clickGroup() {
                let that = this;
                that.groupDiagloSign = true;

                setTimeout(function () {
                    that.$refs.groupTreeData.setCheckedKeys(that.formData.groupIdList, true);
                }, 100);
            },

            //点击选择所属角色
            clickRole() {
                let that = this;
                that.roleDiagloSign = true;

                setTimeout(function () {
                    that.$refs.roleTreeData.setCheckedKeys(that.formData.roleIdList, true);
                }, 100);
            },


            //页面间传参
            getParams: function () {

                let that = this;
                //取到路由带过来的参数
                let routerParams = this.$route.query;
                // 将数据放在当前组件的数据内
                this.parameter = routerParams;
                debugger;
            },

            //编辑
            editUser() {
                debugger;
                let that = this;
                console.log(that.parameter);
                this.parameter.params = 'edit';
                this.editPara='edit';
                console.log(that.parameter);
            },

            //提交表单
            submitForm(formName) {
                let that = this;
                //提交
                debugger;
                that.$refs[formName].validate((valid) => {
                    if (valid) {
                        const loading = this.$loading({
                            lock: true,
                            text: 'Loading',
                            spinner: 'el-icon-loading',
                        });
                        if(this.parameter.params=='edit'){
                            var method = 'put';//修改提交
                        }else{
                            method = 'post';//添加提交
                        }
                        this.$http({
                            method: method,
                            url: userUrl,
                            baseURL: '/api',
                            data: {
                                id: that.formData.id,
                                accountName: that.formData.accountName,
                                userName: that.formData.userName,
                                emailAddress:that.formData.emailAddress,
                                groupIdList: that.formData.groupIdList,
                                roleIdList: that.formData.roleIdList,
                                summary: that.formData.summary
                            }
                        }).then(function (response) {
                            if (response.data.code==200) {
                                if (!response.data.data) {
                                    return;
                                }
                                Message.success('提交用户信息成功');
                                that.editPara = 'see';
                                that.parameter.id = response.data.data.id ;
                                that.$router.push({
                                    path:'/mainPage/userManage',
                                });
                                // that.initiaView();
                            } else {
                                Message.success('提交用户信息失败');
                            }
                            loading.close();
                            that.editPara = 'see';
                        }).catch(function (err) {
                            Message.error('提交用户信息失败');
                            console.log(err);
                            loading.close();
                        });

                    } else {
                        console.log('提交信息校验不通过，请修改输入信息!!');
                        return false;
                    }
                });
                },



            //返回
            backOffBtn: function () {
                this.$router.go(-1);
            },

            //取消-组弹框
            orgCancel() {
                let that = this;
                that.groupDiagloSign = false;
            },

            //确定-组弹框
            groupDetermine() {
                debugger
                let that = this;
                let selectGroup = that.$refs.groupTreeData.getCheckedNodes(false);
                let transformDataGroup = [];
                for (let i = 0; i < selectGroup.length; i++) {
                    transformDataGroup.push(selectGroup[i]);
                }
                that.affGroup = transformDataGroup;
                that.groupDiagloSign = false;
                that.formData.groupIdList = that.$refs.groupTreeData.getCheckedKeys(false);
            },

            //取消-角色弹框
            roleCancel() {
                let that = this;
                that.roleDiagloSign = false;
            },

            //确定-角色弹框
            roleDetermine() {
                let that = this;
                let selectRole = that.$refs.roleTreeData.getCheckedNodes(true);
                let transformDataRole = [];
                for (let i = 0; i < selectRole.length; i++) {
                    transformDataRole.push(selectRole[i]);
                }
                that.affRole = transformDataRole;
                that.roleDiagloSign = false;
                that.formData.roleIdList = that.$refs.roleTreeData.getCheckedKeys(true);
            },

            //初始化-查看
            initiaView() {
                let that = this;
                const loading = this.$loading({
                    lock: true,
                    text: 'Loading',
                    spinner: 'el-icon-loading',
                });
                this.$http({
                    method: 'get',
                    url: viewUrl,
                    baseURL: '/api',
                    params: {
                        'id':that.parameter.id
                    }
                }).then(function (response) {
                    if (response.data.code==200) {
                        if (!response.data.data) {
                            return;
                        }
                        that.formData = response.data.data.msUser;
                        if (that.formData.summary === null) {
                            that.formData.summary = '';
                        }
                        //角色
                        that.roleTreeDisorde = response.data.data.bgRoleList;
                        that.affRole = new Array();
                        var roleIdList = new Array();
                        for (let j = 0; j < that.roleTreeDisorde.length; j++) {
                            that.affRole.push(that.roleTreeDisorde[j]);
                            roleIdList.push(that.roleTreeDisorde[j].id);

                        }
                        that.formData.roleIdList = roleIdList;

                        //组
                        debugger;
                        that.groupTreeDisorde = response.data.data.msGroupsList;
                        that.affGroup = new Array();
                        var groupIdList = new Array();
                        for (let j = 0; j < that.groupTreeDisorde.length; j++) {
                            that.affGroup.push(that.groupTreeDisorde[j]);
                            groupIdList.push(that.groupTreeDisorde[j].id);
                        }
                        that.formData.groupIdList = groupIdList;

                    }
                }).catch(function (err) {
                    console.log(err);
                    loading.close();
                });
            },

            //添加-初始化组
            initialGroupAdd(){
                let that=this;
                //获取组
                const loading = this.$loading({
                    lock: true,
                    text: 'Loading',
                    spinner: 'el-icon-loading',
                });

                that.$http({
                    method: 'get',
                    url: groupUrl,
                    baseURL:'/api',
                    params: {
                    }
                }).then(function(response){
                    if(response.data.code==200) {
                        if(!response.data.data){
                            return;
                        }
                        let newdata=response.data.data.groupInfo;
                        let getJsonTree=function(newdata,parentId){
                            let itemArr=[];
                            for(let i=0;i<newdata.length;i++){
                                let node=newdata[i];
                                if(node.parentId==parentId ){
                                    let newNode={id:node.id,
                                        groupName:node.groupName,
                                        parentId:node.parentId,
                                        description:node.description,
                                        children:getJsonTree(newdata,node.id)};
                                    itemArr.push(newNode);
                                }
                            }
                            return itemArr;
                        };
                        that.groupTreeData=getJsonTree(newdata,'-1');
                    }else{
                        Message.error('获取组数据失败');
                    }
                    that.formData.affGroupFlag=false;
                    loading.close();
                }).catch(function(err){
                    Message.error('获取组数据失败');
                    loading.close();
                });
            },

            //添加-初始化角色
            initialRoleAdd(){
                let that=this;
                const loading = this.$loading({
                    lock: true,
                    text: 'Loading',
                    spinner: 'el-icon-loading',
                });
                // 获取角色
                that.$http({
                    method: 'get',
                    url: roleUrl,
                    baseURL:'/api'
                }).then(function(response){
                    if(response.data.code=200) {
                        if(!response.data.data){
                            return;
                        }
                        var newdata=response.data.data.roleInfos;

                        var getJsonTree=function(newdata,parentId){
                            var itemArr=[];
                            for(var i=0;i<newdata.length;i++){
                                var node=newdata[i];
                                //data.splice(i, 1)
                                if(node.parentId==parentId ){
                                    var newNode={id:node.id,
                                        roleName:node.roleName,
                                        parentId:node.parentId,
                                        description:node.description,
                                        createBy:node.createBy,
                                        createDate:node.createDate,
                                        updateBy:node.updateBy,
                                        updateDate:node.updateDate,
                                        children:getJsonTree(newdata,node.id)};
                                    itemArr.push(newNode);
                                }
                            }
                            return itemArr;
                        };

                        that.roleTreeData=getJsonTree(newdata,'-1');

                    }else{
                        Message.error('获取角色失败');
                    }
                    that.formData.affRoleFlag=false;
                    loading.close();
                }).catch(function(err){
                    console.log(err);
                    Message.error('获取角色失败');
                    loading.close();
                });

            },
        },

        created:function(){
            this.getParams();
        },

        watch: {
            // 监测路由变化,只要变化了就调用获取路由参数方法将数据存储本组件即可
            '$route': 'getParams'
        },
        mounted(){
            let that = this;
            if(that.parameter.params=='add'){
                //添加-初始化组
                that.initialGroupAdd();
                //添加-初始化角色
                that.initialRoleAdd();

            }else{
                that.initialGroupAdd();
                that.initialRoleAdd();
                //查看或者编辑
                that.initiaView();
                if(that.parameter.params=='see'){
                    that.editPara='see'
                }else{
                    that.editPara = 'edit';
                }


            }

            //获取所有用户，做重名校验
            const loading = that.$loading({
                lock: true,
                text: 'Loading',
                spinner: 'el-icon-loading',
            });
            that.$http({
                method: 'get',
                url: userUrl,
                baseURL:'/api',
                params:{
                    'userName':'',
                    'stateValue':-1,
                },
            }).then(function(response){
                if(response.data.code==200) {
                    if(!response.data.data){
                        return;
                    }
                    that.allUser=response.data.data.userInfos;
                }else{
                    Message.error('获取用户数据失败');
                }
                loading.close();
            }).catch(function(err){
                console.log(err);
                Message.error('获取用户数据失败');
                loading.close();
            });


        },
    }
</script>

<style scoped>
    .cardButton{
        line-height: 51px;
        margin-top: -19px
    }

    .width77{
        width: 77%;
    }

    .buttonLineHeight{
        line-height: 60px;
    }

    /*计数*/
    .countNumber{
        margin-right: 23%;
    }

    .submitButton{
        margin-left: 19%;
    }

    .dialogHeght{
        /*min-height: 300px;*/
        /*max-height: 500px;*/
        height: 300px;
        overflow-y: auto;
    }

    .cardWidth{
        width: 100%;
    }
</style>